package scatter.wxcp.rest.notify;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.message.WxCpMessage;
import me.chanjar.weixin.cp.bean.messagebuilder.TextBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import scatter.common.rest.monitor.MonitorTool;
import scatter.common.rest.notify.AbstractNotifyListener;
import scatter.common.rest.notify.INotifyListener;
import scatter.common.rest.notify.NotifyParam;
import scatter.common.rest.tools.InterfaceTool;
import scatter.wxcp.rest.config.WxCpConfig;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 默认的企业微信通知
 * </p>
 *
 * @author yangwei
 * @since 2021-08-25 13:35
 */
@Slf4j
public class DefaultWxCpNotifyListenerImpl extends AbstractNotifyListener implements  InterfaceTool {

	/**
	 * 暂agencyId从ext中取
	 */
	private static final String AGENT_ID_KEY = "wx_cp_agency_id";


	@Autowired
	private IWxCpNotifyAgencyIdResolver iWxCpNotifyAgencyIdResolver;


	@Override
	protected String supportType() {
		return NotifyParam.Type.wxcp.name();
	}

	@Override
	public void doNotify(NotifyParam notifyParam) {
		Integer agencyId = resolveAgentId(notifyParam.getExt());
		if (agencyId == null) {
			agencyId = iWxCpNotifyAgencyIdResolver.resolve(notifyParam);
		}
		if (agencyId == null) {
			log.warn("企业微信通知未获取到agencyId，将不会发送通知，通知参数={}",toJsonStr(notifyParam));
			return;
		}
		String toUser = resolveToUser(notifyParam.getToUser());
		// 获取格式化内容并换行展示
		String content = formatParam(notifyParam).stream().collect(Collectors.joining("\n"));
		WxCpMessage wxCpMessage = WxCpMessage.TEXT().content(content).toUser(toUser).build();
		WxCpService cpService = WxCpConfig.getCpService(agencyId);
		try {
			cpService.getMessageService().send(wxCpMessage);
		} catch (WxErrorException e) {
			log.error("企业微信通知异常，type={},agent_id_key={},content={}",supportType(),AGENT_ID_KEY,wxCpMessage.toJson(),e);
			MonitorTool.count("notify.exception","企业微信通知异常","supportType",supportType());
		}

	}

	/**
	 * 获取agencyId
	 * @param ext
	 * @return
	 */
	private Integer resolveAgentId(Map<String,Object> ext){
		if (ext == null) {
			return null;
		}
		return (Integer) ext.get(AGENT_ID_KEY);
	}

	/**
	 * 发送用户
	 * @param toUser
	 * @return
	 */
	private String resolveToUser(List<String> toUser){
		if (isEmpty(toUser)) {
			// 发给你那有人
			return "@all";
		}
		return toUser.stream().collect(Collectors.joining("|"));
	}
}
